package cn.kgc.controller;


import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

/**
 * @描述
 * @author：LY
 * @2018/11/6 15:51
 */
@Controller
public class download {

    @RequestMapping(value = "download",method = RequestMethod.GET)
    public ResponseEntity<byte[]> download(HttpServletRequest request,String filename) throws IOException {
        String path = request.getSession().getServletContext().getRealPath("/upload");
        File file = new File(path+File.separator+filename);
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentDispositionFormData("attachment",new String(filename.getBytes("utf-8"),"iso-8859-1"));
        httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        ResponseEntity responseEntity = new ResponseEntity(FileUtils.readFileToByteArray(file),httpHeaders,HttpStatus.OK);
        return responseEntity;
    }

  /*  @RequestMapping("download")
    //txt String 字符 jpg byte[] 字节  通用
    public ResponseEntity<byte[]> downLoad(HttpServletRequest request,String filename) throws IOException {
        //1 根据用户要下载的文件名称,从磁盘查找这个文件
        String path=request.getSession().getServletContext().getRealPath("/upload");
        File downFile=new File(path+ File.separator+filename);
        // 判断文件是否存在用户否有权限进行下载
        //2 将这个文件以流的形式写出到页面给用户下载
        //ResponseEntity(T body, MultiValueMap<String, String> headers, HttpStatus statusCode) {
        HttpHeaders headers=new HttpHeaders();
        // URLEncoder.encode("中国人","utf-8");
        //  String s=new String("中国人".getBytes(),"utf-8");
        //通过用户以什么形式进行下载  iso-8859-1 URLEncoder
        headers.setContentDispositionFormData("attachment",new String(filename.getBytes("utf-8"),"iso-8859-1"));
        //以流的形式进行文件的传输
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

        ResponseEntity result=new ResponseEntity(FileUtils.readFileToByteArray(downFile),headers,HttpStatus.OK);
        return result;
    }*/



}